import React, { useEffect, useState } from 'react'
import useForm from "rc-form-hooks"
import { connect } from 'dva'
import { Form, Input, DatePicker, Button, Select, message } from 'antd'
import './index.styl'

const { Option } = Select

function HeaderSearch({ type, dispatch, searchBtn, query, deviceRepair: { stateOptions }}) {
    const { getFieldDecorator, validateFields, resetFields, setFieldsValue } = useForm()
    // 获取状态选项
    useEffect(() => {
        if (type !== 'complainSingle') {
            dispatch({
                type: getStatusOptions[type],
            })
        }
        if (type === 'repairSingle' && query.codeText ) {
           
            if (query.codeText) {
                // 是否从工作台过来，是得优先展示工作台得信息
                setFieldsValue({
                    'state': query.codeText
                })
            } else {
                // 没有关闭页面得前提下，是否有缓存，有则优先展示缓存数据
                const repairSingle = localStorage.getItem('repairSingle')
                if (repairSingle) {
                    setFieldsValue(JSON.parse(repairSingle))
                }
            }
        }
    },[dispatch, getStatusOptions, query.codeText, setFieldsValue, type])

    const getStatusOptions = {
        'repairSingle': 'deviceRepair/getRepairStatus', // 维修
        'reformSingle': 'deviceRepair/getReftStatusAll', // 整改
        'complainSingle': 'deviceRepair/getComplaintStatus', // 整改
    }

    const actions = {
        'repairSingle': 'deviceRepair/getSingleList', // 维修
        'reformSingle': 'deviceRepair/getReftList', // 整改
        'complainSingle': 'deviceRepair/getComplaintList', // 投诉
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        validateFields()
        .then((values) => {
            searchBtn({
                ...values,
                repairStartTime: values['repairStartTime'] && values['repairStartTime'].format('YYYY-MM-DD'),
                repairEndTime: values['repairEndTime'] && values['repairEndTime'].format('YYYY-MM-DD'),
                current: '1',
                size: '10', 
            })
        })
        .catch(e => message.error(e.message))
    }

    // 选择时间对应的模块标题
    const timeTitle = {
        'repairSingle': '报修时间',
        'reformSingle': '整改截止时间',
        'complainSingle': '投诉时间',
    }

    // 开始时间
    const [startTime, setStartTime] = useState()

    // 结束时间
    const [endTime, setEndTime] = useState()

    // 重置
    const onReset = () => {
        setStartTime()
        setEndTime()
        resetFields();
        // 清除缓存数据
        dispatch({type: 'deviceRepair/clean'})
        dispatch({
            type: actions[type],
            payload: {
                current: '1',
                size:'10'
            }
        });
    }

    // 开始时间
    const selectStartTime = (time) => {
        setStartTime(time)
    }

    // 开始时间
    const selectEndTime = (time) => {
        setEndTime(time)
    }

    // 设置开始不能选择的时间
    const disabledStartDate = startTime => {
        if (!startTime || !endTime) {
            return false
        }
        return startTime.valueOf() > endTime.valueOf()
    }
    
    //设置结束不能选择的时间
    const disabledEndDate = endTime => {
        if (!endTime || !startTime) {
            return false
        }
        return endTime.valueOf() <= startTime.valueOf()
    }

    return(
        <div className="equipmentMaintenance-form">
            <Form name="nest-messages" className="self-form" onSubmit={handleSubmit}>
            <div className="flex">
                <Form.Item label="设备名称">
                {getFieldDecorator('deviceName', {
                    rules: [{ required: false }],
                })(
                    <Input className="self-input" placeholder="请输入" />
                )}
                </Form.Item>
                <Form.Item label="设备使用部门">
                {getFieldDecorator('groupName', {
                    rules: [{ required: false }],
                })(
                    <Input className="self-input" placeholder="请输入" />
                )}
                </Form.Item>
                <Form.Item label="报修员">
                {getFieldDecorator('repairClerk', {
                    rules: [{ required: false }],
                })(
                    <Input className="self-input" placeholder="请输入" />
                )}
                </Form.Item>
                <Form.Item label="维修员">
                {getFieldDecorator('repairman', {
                    rules: [{ required: false }],
                })(
                    <Input className="self-input" placeholder="请输入" />
                )}
                </Form.Item>
                <Form.Item label="维修员电话">
                {getFieldDecorator('repairmanTel', {
                    rules: [{ required: false }],
                })(
                    <Input className="self-input" placeholder="请输入" rows={10}/>
                )}
                </Form.Item>
            </div>
            <div className="flex">
                <Form.Item label="状态" style={{ display: type === 'complainSingle' ? 'none' : '' }}>
                    {getFieldDecorator('state', {
                        initialValue: '',
                        rules: [{ required: false }],
                    })(
                        <Select
                            placeholder="Select province"
                            className="self-select"
                            placeholder="请选择"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                        >
                            <Option value=''>全部</Option>
                            {
                                type !== 'complainSingle' && stateOptions && stateOptions.map((item) => {
                                    return (<Option value={item.code} key={item.code}>{item.message}</Option>)
                                })
                            }
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label={timeTitle[type]}>
                    {getFieldDecorator('repairStartTime', {
                        rules: [{ required: false }],
                    })(
                        <DatePicker 
                        className="self-date" 
                        showToday={false} 
                        placeholder="选择开始时间"
                        onChange={selectStartTime}
                        disabledDate={disabledStartDate}
                        allowClear={false}
                        />
                    )}
                </Form.Item>
                <Form.Item label="">
                    {getFieldDecorator('repairEndTime', {
                        rules: [{ required: false }],
                    })(
                        <DatePicker 
                        className="self-date" 
                        showToday={false} 
                        placeholder="选择结束时间"
                        disabledDate={disabledEndDate}
                        onChange={selectEndTime}
                        allowClear={false}
                        />
                    )}
                </Form.Item>
                <Button className="blue-button" htmlType="submit">查询</Button>
                <Button className="white-button" onClick={() => onReset()}>重置</Button>
            </div>
            </Form>
        </div>
    )
}

export default connect(({ deviceRepair }) => ({
    deviceRepair
}))(HeaderSearch)